import { onMounted,onUnmounted , isRef, watch , unref } from 'vue'
import type { Ref } from 'vue'
const useEventListener = (target: Ref<EventTarget | null> | EventTarget,eventName:string,callBack:(e:Event)=>any) =>{
    onMounted(()=>{
        if(isRef(target)){
            watch(target,(newValue,oldValue)=>{
                newValue?.addEventListener(eventName,callBack)
                oldValue?.removeEventListener(eventName,callBack)
            })
        }else {
            target.addEventListener(eventName,callBack)
        }
        
    })
    onUnmounted(()=>{
     unref(target)?.removeEventListener(eventName,callBack)
        
    })
}

export default useEventListener